<script setup>
import {onMounted, ref} from 'vue'
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NTabPane,
  NTabs,
  NImage,
  NUpload,
  useMessage,
  NLayout,
  NLayoutContent, NSelect
} from 'naive-ui'
import { useI18n } from 'vue-i18n'
import CommonPage from '@/components/page/CommonPage.vue'
import { useUserStore } from '@/store'
import api from '@/api'
import {getToken, is, renderIcon} from '~/src/utils'
import {useCRUD} from "@/composables";
import CrudModal from "@/components/table/CrudModal.vue";
import Main from './main.vue'
import TheIcon from "@/components/icon/TheIcon.vue";
const { t } = useI18n()
const userStore = useUserStore()
const isLoading = ref(false)
const base_path = import.meta.env.VITE_BASE
const message = useMessage()


const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '客户',
  initForm: {},
  doCreate: api.createCustomer,
  doDelete: api.deleteCustomer,
  doUpdate: api.updateCustomer,
  refresh: () => $table.value?.handlerefresh(),
})

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  show:false,
  config:[],
  search_loading:false,
  user_all: [],
  customer_list_online:[],
  customer_list:[],
  online:1,
  keyword:"",
  loading:false,
  card_loading:false,
  select_id:"",
  select_customer:{
    draw:false,
    name:"--",
    card_number:"--",
    user_level_name:"--",
    mobile:"--",
    bi_date:"--",
    sex:"--",
    hkqd:"--",
    age:"--",
    created_at:"--",
    last_come:"--",
    parent_name:"--",
    butler_name:"--",
    totals:{
      weimei:0,
      cdp:0,
      fujia:0,
      other:0,
      buy_money:0,
      cases:0,
      appoint_count:0,
      return_count:0
    }
  },
  hkqdData:[]
});

onMounted(() => {
  select_tab("chap1")
  get_config()
})

function get_config() {
  if (data.config.length === 0) {
    api.getConfig().then((res) => {
      data.config = res.data
    })
  }
  if (data.config.length === 0) {
    api.getUserList().then((res) => {
      data.user_all = res.data
    })
  }
}

function get_customers(){
  api.getCustomers({
    online:data.online,
    keyword:data.keyword
  }).then((res) => {
    const items = Array.isArray(res?.data?.items) ? res.data.items : []
    const seen = new Set()
    const uniqueItems = []
    for (const it of items) {
      const uid = (it && (it.user_id ?? it.id))
      if (uid == null) {
        continue
      }
      if (!seen.has(uid)) {
        seen.add(uid)
        uniqueItems.push(it)
      }
    }
    if(data.online===1){
      data.customer_list_online = uniqueItems
    }else{
      data.customer_list = uniqueItems
      data.loading = false
    }
    if(uniqueItems.length>0){
      select_customer(uniqueItems[0])
    }

  })
}

function more_info(item){
  data.select_id = item.user_id
  api.getCustomer({
    user_id:data.select_id,
  }).then((res) => {
     data.select_customer = res.data
     data.show = true
     data.select_customer.draw = true
  })
}

function select_tab(type){
  if(type==="chap1"){
    data.online=1
    data.keyword=""
  }else{
    data.online=null
  }
  get_customers()
}

function search_customer(){
  data.loading = true
  get_customers()
}

function select_customer(item){
  if(data.select_id === item.user_id){ return;}
  data.select_id = item.user_id
  data.card_loading = true
  api.getCustomer({
    user_id:data.select_id,
  }).then((res) => {
     data.select_customer = res.data
     $message.success("已选择客户:"+data.select_customer.name)
      data.card_loading = false
  })

}

const validate = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
  mobile: [
    {
      required: true,
      message: '请输入手机号码',
      trigger: ['input', 'blur', 'change'],
    },
  ],
}

function on_refx(){
  get_customers()
}

function search_customer2(query) {
  data.search_loading = true
  api.getCustomers({keyword: query}).then((res) => {
    data.select_customers = res.data.items
    data.search_loading = false
  })
}

function add_customer(){
  data.select_customer = {
    draw:true,
    name:"",
    card_number:"--",
    user_level_name:"--",
    mobile:"--",
    bi_date:"--",
    sex:"--",
    hkqd:"--",
    identity:"--",
    age:"--",
    created_at:"--",
    last_come:"--",
    totals:{
      weimei:0,
      cdp:0,
      fujia:0,
      other:0,
      buy_money:0,
      cases:0,
      appoint_count:0,
      return_count:0
    }
  }
}
</script>

<template>

<AppPage :show-footer="false" >
    <n-grid x-gap="12" :cols="2" style="height: 100%" >
    <n-gi>
      <n-card style="height: 100%" title="客户选择" size="small"  :segmented="{content: true,footer: 'soft',}">
        <n-tabs type="segment" animated :on-update:value="select_tab">
          <n-tab-pane name="chap1" tab="在店客户">
            <n-scrollbar style="max-height: calc(100vh - 250px);padding:0">

              <n-grid x-gap="12"  :cols="2"  >
                 <n-gi  >
                <n-card @click="add_customer" embedded  class="customer_card" hover:card-shadow   size="small"   style="background: #efefef;cursor: pointer" :segmented="{ content: true, footer: 'soft'}">
                 <div style="justify-content: center;align-items: center;height: 120px;width: 100%;display: flex">
                 <TheIcon icon="material-symbols:add" :size="38" style="margin: auto" />
                 </div>
               </n-card>
                 </n-gi>
           <n-gi v-for="item in data.customer_list_online" >
            <n-card embedded  class="customer_card" @click="select_customer(item)" hover:card-shadow   size="small" :segmented="{content: true,footer: 'soft',}">
              <template #header>
                <div style="display: flex; align-items: center;" >
                  <NAvatar :src="item.photo"  style="width: 30px; height: 30px; margin-right: 10px;border-radius: 50%" />
                  <span>{{item.name}}</span>
                </div>
              </template>
              <template #header-extra>
                <NTag type="error" v-if="item.user_id===data.select_id">已选择</NTag>&nbsp;
                <NTag type="primary">{{item.user_level_name}}</NTag>

              </template>
              <template #footer>
                <span color="#ef504e"></span>
                <n-flex justify="space-between" size="large">
                  <div>病历号: <span>{{item.card_number}}</span> </div>
                  <div>电话: <span>{{item.mobile}}</span></div>
                </n-flex>
                <n-flex justify="space-between" size="large">
                  <div>渠道: <span>{{item.hkqd}}</span> </div>
                </n-flex>
                <n-flex justify="space-between" size="large">
                  <div>主管: <span>{{item.butler}}</span> </div>
                   <div><NButton  type="primary" size="tiny"   @click="more_info(item)">
                     <TheIcon icon="material-symbols:playlist-add-check-rounded" :size="18" class="mr-5" />操作</NButton></div>

                </n-flex>
              </template>
            </n-card>
           </n-gi>
           </n-grid>
            </n-scrollbar>
          </n-tab-pane>
          <n-tab-pane name="chap2" tab="搜索客户">
            <NInput size="large" @change="search_customer" v-model:value="data.keyword" :loading="data.loading" clearable type="text" placeholder="请输入客户姓名/电话/病历号"/>
            <n-scrollbar style="max-height: calc(100vh - 250px);padding:0">
            <n-card v-for="item in data.customer_list" embedded  class="customer_card" hover:card-shadow  @click="select_customer(item)" size="small" :segmented="{
                    content: true,
                    footer: 'soft',
                  }"
            >
              <template #header>
                <div style="display: flex; align-items: center;" >
                  <NAvatar :src="item.photo"  style="width: 30px; height: 30px; margin-right: 10px;border-radius: 50%" />
                  <span>{{item.name}}</span>
                </div>
              </template>
              <template #header-extra>
                <NTag type="error" v-if="item.user_id===data.select_id">已选择</NTag>&nbsp;
                <NTag type="primary">{{item.user_level_name}}</NTag>

              </template>
              <template #footer>
                <span color="#ef504e"></span>
                <n-flex justify="space-between" size="large">
                  <div>病历号: <span>{{item.card_number}}</span> </div>
                  <div>电话: <span>{{item.mobile}}</span></div>
                </n-flex>
                <n-flex justify="space-between" size="large">
                  <div>渠道: <span>{{item.hkqd}}</span> </div>
                </n-flex>
                <n-flex justify="space-between" size="large">
                  <div>主管: <span>{{item.butler}}</span> </div>
                   <div><NButton  type="primary" size="tiny"   @click="more_info(item)">
                     <TheIcon icon="material-symbols:playlist-add-check-rounded" :size="18" class="mr-5" />操作</NButton></div>

                </n-flex>
              </template>
            </n-card>

            </n-scrollbar>
          </n-tab-pane>
        </n-tabs>
      </n-card>
    </n-gi>
    <n-gi>
      <n-card size="small"  style="height: 100%" :segmented="{content: true,footer: 'soft',}">
        <n-spin :show="data.card_loading" style="--n-opacity-spinning:0.1">
        <n-divider>基本资料</n-divider>
        <n-descriptions label-placement="left" bordered :column="2">
            <n-descriptions-item label="姓名">{{data.select_customer.name}}</n-descriptions-item>
            <n-descriptions-item label="病历号">{{data.select_customer.card_number}}</n-descriptions-item>
            <n-descriptions-item label="会员级别">{{data.select_customer.user_level_name}}</n-descriptions-item>
            <n-descriptions-item label="电话">{{data.select_customer.mobile}}</n-descriptions-item>
            <n-descriptions-item label="会员生日">{{data.select_customer.bi_date}}</n-descriptions-item>
            <n-descriptions-item label="身份证">{{data.select_customer.identity}}</n-descriptions-item>
            <n-descriptions-item label="会员性别">{{data.select_customer.sex}}</n-descriptions-item>
            <n-descriptions-item label="渠道来源">{{data.select_customer.hkqd}}</n-descriptions-item>
            <n-descriptions-item label="会员年龄">{{data.select_customer.age}}</n-descriptions-item>
            <n-descriptions-item label="登记时间">{{data.select_customer.created_at}}</n-descriptions-item>
            <n-descriptions-item label="上次到店">{{data.select_customer.last_come}}</n-descriptions-item>
          <n-descriptions-item label="介绍人">{{data.select_customer.parent_name}}</n-descriptions-item>
          <n-descriptions-item label="所属顾问">{{data.select_customer.butler_name}}</n-descriptions-item>
          </n-descriptions>
        <n-divider>资产剩余</n-divider>
        <n-descriptions label-placement="left" bordered :column="2">
            <n-descriptions-item label="储值金余额">{{(Number(data.select_customer.totals?.weimei) || 0).toFixed(2)}}</n-descriptions-item>
            <n-descriptions-item label="积分余额">{{Number(data.select_customer.totals?.cdp || 0)}}</n-descriptions-item>
            <n-descriptions-item label="优惠券余额">{{Number(data.select_customer.totals?.fujia || 0)}}</n-descriptions-item>
            <n-descriptions-item label="赠送金">{{Number(data.select_customer.totals?.free || 0)}}</n-descriptions-item>
          </n-descriptions>
        <n-divider>统计汇总</n-divider>
        <n-descriptions label-placement="left" bordered :column="2">
            <n-descriptions-item label="合计消费">{{Number(data.select_customer.totals?.buy_money || 0)}}万</n-descriptions-item>
            <n-descriptions-item label="合计操作">{{Number(data.select_customer.totals?.cases || 0)}}</n-descriptions-item>
            <n-descriptions-item label="预约次数">{{Number(data.select_customer.totals?.appoint_count || 0)}}</n-descriptions-item>
            <n-descriptions-item label="回访次数">{{Number(data.select_customer.totals?.return_count || 0)}}</n-descriptions-item>
          </n-descriptions>
        </n-spin>
      </n-card>
    </n-gi>
  </n-grid>

  <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      @save="handleSave"
    >
      <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :disabled="modalAction === 'view'"
        :rules="validate"
      >
        <NFormItem label="客户姓名" path="name">
          <NInput v-model:value="modalForm.name" placeholder="请输入客户姓名" />
        </NFormItem>
        <NFormItem label="手机号码" path="mobile">
          <NInput v-model:value="modalForm.mobile" placeholder="请输入手机号码" />
        </NFormItem>
        <NFormItem label="介绍人" path="card_number">
          <NSelect
                     v-model:value="modalForm.card_number"
                     :options="data.select_customers"
                     placeholder="输入姓名/病历号/手机号搜索"
                     filterable
                     label-field="all_name"
                     value-field="card_number"
                     style="width:100%"
                     :loading="data.search_loading"
                     remote
                     clearable
                     @search="search_customer2"/>
        </NFormItem>
<!--        <NFormItem label="身份证件" path="identity">-->
<!--          <NInput v-model:value="modalForm.identity" placeholder="请输入身份证件" />-->
<!--        </NFormItem>-->
        <NFormItem label="出生日期" path="bi_date">
          <n-date-picker
            v-model:formatted-value="modalForm.bi_date"
            value-format="yyyy.MM.dd"
            type="date"
            clearable
            placeholder="请输入出生日期"
            style="width: 100%;"
          />
        </NFormItem>
        <NFormItem label="获客渠道" path="hkqd">
          <NSelect
                v-model:value="modalForm.hkqd"
                :options="data.config.hkqd"
                placeholder="请选择获客渠道"
                label-field="name"
                value-field="name"
              />
        </NFormItem>

        <NFormItem label="所属顾问" path="butler_id">
          <NSelect
                v-model:value="modalForm.butler_id"
                :options="data.user_all"
                placeholder="请选择所属顾问"
                label-field="name"
                value-field="id"
                filterable
              />
        </NFormItem>

      </NForm>
    </CrudModal>


  <n-drawer v-model:show="data.select_customer.draw" width="90%">
        <Main :info-data="data.select_customer" @call-parent="on_refx"/>
  </n-drawer>


</AppPage>
</template>

<style scoped>
.customer_card{
  margin: 10px 0;
}
</style>